/***************************************************************************\
 * The Mattise Kernel														*
 * Copyright 2007 Matthew Iselin											*
 * Licensed under the GPL													*
 *																			*
 * string_util.cc															*
 *																			*
 * String utility functions, most of which are designed for speed.			*
 *																			*
\***************************************************************************/

// includes
#include <system.h>
#include <stdio.h>

// fast substring (casts to the largest possible type)
void substr( char* dest, const char* src, int start, int end )
{
	// index
	int i;
	
	// length
	int len = end - start;
	
	// find out whether len is even
	if( len % 2 == 0 )
	{
		// find out if it's divisible by 4
		if( len % 4 == 0 )
		{
			// find out if it's divisible by 8
			if( len % 8 == 0 )
			{
				// we can use an 8 byte pointer
				for( i = start; i < end; i += 8 )
					*((unsigned long long*) &dest[i-start]) = *((unsigned long long*) &src[i]);
			}
			else
			{
				// 4 byte pointer
				for( i = start; i < end; i += 4 )
				{
					*((uint_t*) &dest[i-start]) = *((uint_t*) &src[i]);
				}
			}
		}
		else
		{
			// 2 byte pointer
			for( i = start; i < end; i += 2 )
				*((ushort_t*) &dest[i-start]) = *((ushort_t*) &src[i]);
		}
	}
	else
	{
		// 1 byte pointer
		for( i = start; i < end; i++ )
			dest[i-start] = src[i];
	}
}

// gets the length of a string
int strlen( const char* str )
{
	int i = 0;
	while( *str++ ) { i++; };
	return i;
}

// fast string copy
int strcpy( char* dest, const char* src )
{
	// copy them
	substr( dest, src, 0, strlen( src ) );
	
	// return the full size
	return strlen( src );
}

// string comparison - could be sped up in the same way as substr
int strcmp( const char* str1, const char* str2, int len )
{
	for( int i = 0; i < len; i++ )
	{
		if( str1[i] != str2[i] )
			return 0;
	}
	return 1;
}

// finds a character in a string - could be sped up
int find( const char* str, const char find, int start, int end )
{
	for( int i = start; i < end; i++ )
		if( str[i] == find )
			return i;
	return -1;
}
